/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2023-01-17
 * Time:17:06
 */
class Node{
    int val;
    Node left;
    Node right;
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}
class Solution {
    private Node pre;
    private Node cur;
    public Node treeToDoublyList(Node root) {
        if(root==null){
            return null;
        }
        tree(root);
        if(pre==null){
            pre=root;
        }
        while(pre.left!=null){
            pre=pre.left;
        }
        pre.left=cur;
        cur.right=pre;
        return pre;
    }
    public void tree(Node root){
        //中序遍历
        if(root.left!=null){
            tree(root.left);
        }
        pre=cur;
        cur=root;
        if(pre!=null){
            pre.right=cur;
            cur.left=pre;
        }
        if(root.right!=null){
            tree(root.right);
        }
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null){
            return null;
        }
        if(root==p||root==q){
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null&&right!=null){
            return root;
        }
        if(right!=null){
            return right;
        }
        if(left!=null){
            return left;
        }
        return null;
    }
}
public class Test {
}
